﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace BDM
{
    class Message
    {
        public Message()
        {
            if (!Directory.Exists("idfiles"))
            {
                Directory.CreateDirectory("idfiles");
            }
        }

        public void Send(string Text, string[] ID_Array)
        {
            for (int i = 0; i < ID_Array.Length; i++)
            {
                Send(Text, ID_Array[i]);
            }
        }

        public void Send(string Text, string ID)
        {
            if (!File.Exists(@"idfiles\" + ID.ToString() + ".rec"))
            {
                FileStream f = File.Create(@"idfiles\" + ID.ToString() + ".rec");
                f.Close();
            }

            string[] sa = new string[1];
            sa[0] = Text;

            try
            {
                File.WriteAllLines(@"idfiles\" + ID + ".rec", sa);
            }
            catch
            {
                System.Threading.Thread.Sleep(10);
                Send(Text, ID);
            }
        }

        public string Receive(string ID)
        {
            while (true)
            {
                try
                {
                    string sText = "";
                    try
                    {
                        File.Copy(@"idfiles\" + ID.ToString() + ".rec", @"idfiles\" + ID.ToString() + ".recx");
                    }
                    catch { }
                    List<string> file = new List<string>(File.ReadAllLines(@"idfiles\" + ID.ToString() + ".recx"));
                    for (int i = 0; i < file.Count; i++)
                    {
                        sText += file[i].ToString() + "\r\n";
                    }
                    if (file.Count > 0)
                    {
                        file.Clear();
                        File.WriteAllLines(@"idfiles\" + ID.ToString() + ".rec", file.ToArray());
                    }
                    File.Delete(@"idfiles\" + ID.ToString() + ".recx");
                    if (sText.ToString() != "")
                    {
                        return sText;
                    }
                    System.Threading.Thread.Sleep(5000);
                }
                catch { }
            }
        }
    }
}
